<template>
    <div class="mapView">
        <ol-map
            :load-tiles-while-animating="true"
            :load-tiles-while-interacting="true"
            :controls="[]"
            class="map_container"
            style="position: relative; width: 100%; height: 100%"
        >
            <ol-view ref="viewRef" :center="MAP_CENTER" :zoom="MAP_ZOOM" :projection="MAP_PROJECTION" />
            <ol-tile-layer
                v-for="(checkedLayerItem, checkedLayerIndex) in formatedLayerList"
                :key="'checkedLayerIndex' + checkedLayerIndex"
                :z-index="1001"
            >
                <ol-source-tile-wms
                    :url="checkedLayerItem.url"
                    :extent="checkedLayerItem.extent"
                    :layers="checkedLayerItem.layers"
                    styles=""
                    :projection="checkedLayerItem.projection"
                    server-type="geoserver"
                    :transition="0"
                    :params="{}"
                />
            </ol-tile-layer>
            <div class="map-tool-bar">
                <ol-fullscreen-control class="map-tool-item"> </ol-fullscreen-control>
                <ol-switcher-baseLayer-control
                    class="map-tool-item"
                    style="margin-top: 4px"
                    :layers="baseMapLayers"
                    card-direction="left-horizon"
                >
                    <div
                        style="
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            width: 32px;
                            height: 32px;
                            background: rgb(52 53 73 / 70%);
                            backdrop-filter: blur(0);
                            border-radius: 4px;
                            box-shadow: 0 2px 4px 0 rgb(0 0 0 / 50%);
                        "
                    >
                        <el-icon style="font-size: 24px; line-height: 32px; color: #ffffff"><SwitchFilled /></el-icon>
                    </div>
                </ol-switcher-baseLayer-control>
            </div>
        </ol-map>
        <div class="mapview-operation-area">
            <div class="mapview-operation-area-title">
                <el-checkbox :indeterminate="true"> 名称 </el-checkbox>
            </div>
            <!-- <el-input v-model="filterName" class="filter-input" placeholder="图层名称" :prefix-icon="Search" /> -->
            <el-checkbox-group v-model="checkedLayerList" class="layer-list-control" @change="layerCheckHandler">
                <li
                    v-for="(layerItem, layerIndex) in orignTableData"
                    :key="'layeroverview' + layerIndex"
                    class="layer-item-control"
                >
                    <el-checkbox :label="layerItem.name" :value="layerItem">
                        <el-tooltip class="box-item" effect="dark" :content="layerItem.name" placement="top-start">
                            <div style="display: flex">
                                <span
                                    style="
                                        display: flex;
                                        flex: 0 0 20px;
                                        align-items: center;
                                        justify-content: center;
                                        height: 18px;
                                        background: #ffffff;
                                        border: 1px solid;
                                        border-radius: 2px;
                                    "
                                    :style="{
                                        color: layerItem.type == 'coverage' ? '#00C93C' : '#2A78FF',
                                        borderColor: layerItem.type == 'coverage' ? '#00C93C' : '#2A78FF',
                                    }"
                                >
                                    <img v-if="layerItem.type == 'coverage'" :src="rasterImage" />
                                    <img
                                        v-else-if="geometryTypeDic.point.includes(layerItem.type)"
                                        :src="vectorPointImage"
                                    />
                                    <img
                                        v-else-if="geometryTypeDic.line.includes(layerItem.type)"
                                        :src="vectorLineImage"
                                    />
                                    <img
                                        v-else-if="geometryTypeDic.polygon.includes(layerItem.type) || true"
                                        :src="vectorPolygonImage"
                                    />
                                </span>
                                <span style="flex: 1; margin-left: 10px">
                                    {{ layerItem.name }}
                                </span>
                            </div>
                        </el-tooltip>
                    </el-checkbox>
                    <el-popover
                        placement="bottom"
                        popper-class="overview-layer-operation-popover"
                        :hide-after="0"
                        :width="90"
                        trigger="click"
                    >
                        <template #reference>
                            <el-icon><MoreFilled /></el-icon>
                        </template>
                        <ul>
                            <li @click="zoomToLayerHandler(layerItem)">
                                <span
                                    ><el-icon><Location /></el-icon></span
                                ><span class="operation-popover-title">缩放至</span>
                            </li>
                            <li @click="handleLayerEdit(layerItem)">
                                <span><img src="@/assets/images/edit.png" /></span
                                ><span class="operation-popover-title">编辑</span>
                            </li>
                            <li @click="handleLayerEdit(layerItem)">
                                <span><img src="@/assets/images/layers/layer-catch-set.png" /></span>
                                <span class="operation-popover-title">切片设置</span>
                            </li>
                            <li @click="handleLayerEdit(layerItem)">
                                <span><img src="@/assets/images/layers/layer-export.png" /></span>
                                <span class="operation-popover-title">导出</span>
                            </li>
                            <li @click="handleDelete([layerItem.id])">
                                <span><img src="@/assets/images/delete.png" /></span>
                                <span class="operation-popover-title">删除</span>
                            </li>
                        </ul>
                    </el-popover>
                </li>
            </el-checkbox-group>
            <div class="mapview-pagination-area">
                <el-pagination
                    v-if="totalOrignTableData > 10"
                    v-model:current-page="layersQueryFormData.pageNum"
                    v-model:page-size="layersQueryFormData.pageSize"
                    class="layers-pagination"
                    :page-sizes="[10, 20, 50, 100]"
                    :pager-count="1"
                    :background="true"
                    layout="total, prev, slot, next"
                    :total="totalOrignTableData"
                >
                    <template #default>
                        <span style="font-size: 12px; color: #1d2129">
                            {{ `${layersQueryFormData.pageNum}/${totalPages}` }}</span
                        >
                    </template>
                </el-pagination>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts" name="authMenu">
import { MAP_CENTER, MAP_ZOOM, MAP_PROJECTION, DICTIONARY, baseMapLayers } from '@/config/config'
import { Layers } from '@/api/interface/layers'
import vectorPointImage from '@/assets/images/layers/vector-point.png'
import vectorPolygonImage from '@/assets/images/layers/vector-polygon.png'
import vectorLineImage from '@/assets/images/layers/vector-line.png'
import rasterImage from '@/assets/images/layers/raster.png'
import { deleteLayerApi } from '@/api/modules/layers'

//几何类型字典
const geometryTypeDic = DICTIONARY.geometryType

import useLayersFilterModal, { useLayerEditModal, zoomToLayer } from '../hooks'

// 图层编辑相关hook
const layerEditModal = useLayerEditModal()

const mapUrl = import.meta.env.VITE_MAP_SERVER_URL
// 图层过滤相关hook
const layersFilterModal = useLayersFilterModal()
// 数据总条数、查询出的数据、勾选的数据
const { totalOrignTableData, orignTableData, checkedLayerList } = layersFilterModal
// 图层查询表单
const layersQueryFormData = layersFilterModal.layersQueryFormData

// 地图视图ref
const viewRef = ref<any>(null)
// 计算总页数
const totalPages = computed(() => Math.ceil(totalOrignTableData.value / layersQueryFormData.value.pageSize))
// 勾选的图层列表
const formatedLayerList = computed(() => {
    return checkedLayerList.value.map(mapItem => {
        const layerName = mapItem.workspace ? `${mapItem.workspace}:${mapItem.name}` : mapItem.name
        return {
            url: mapUrl + '/wms',
            layers: layerName,
            projection: mapItem.srs || 'EPSG:4326',
            extent: mapItem.extent || [],
        }
    })
})
// 勾选一个时默认缩放过去
watch(
    () => checkedLayerList.value,
    newValue => {
        if (newValue.length == 1) {
            if (viewRef.value) {
                // eslint-disable-next-line @typescript-eslint/no-use-before-define
                zoomToLayerHandler(newValue[0]!)
            }
        }
    },
)
const layerCheckHandler = (value: any) => {
    console.log(value)
}
/**
 * @description: 缩放至图层
 * @param {*} currentLayer 当前选中图层
 * @return {void}
 */
const zoomToLayerHandler = (currentLayer: Layers.ResLayerListItem) => {
    if (checkedLayerList.value.includes(currentLayer)) {
        if (currentLayer.minX && viewRef.value.view.getProjection().getCode() == currentLayer.srs) {
            const extend = [
                Number(currentLayer.minX),
                Number(currentLayer.minY),
                Number(currentLayer.maxX),
                Number(currentLayer.maxY),
            ]
            viewRef.value.fit(extend, { padding: [200, 200, 200, 200] })
        } else {
            zoomToLayer(viewRef, currentLayer)
        }
    } else {
        ElMessage({
            message: '请勾选后再进行缩放！',
            type: 'warning',
        })
    }
}

/**
 * @description: 删除图层
 * @param {*} row 待删除图层
 * @return {*}
 */
const handleDelete = (rowsid: string[]) => {
    ElMessageBox.confirm('确认删除该图层么?', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            deleteLayerApi(rowsid, false).then(res => {
                if (res.code == 200 && res.data && res.data.length > 0) {
                    const existLayerNames = res.data
                        .map((mapItem: { dataName: any }) => {
                            return mapItem.dataName
                        })
                        .join(',')
                    ElMessageBox.confirm(`存在与之关联的图层[${existLayerNames}]，是否强制删除?`, '警告', {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }).then(() => {
                        deleteLayerApi(rowsid, true).then(res => {
                            if (res.code == 200) {
                                ElMessage({
                                    type: 'success',
                                    message: '删除成功',
                                })
                                layersFilterModal.queryLayers()
                            }
                        })
                    })
                } else if (res.code == 200) {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                    layersFilterModal.queryLayers()
                }
            })
        })
        .catch(() => {})
}
/**
 * @description: 图层编辑handler
 * @param {*} row
 * @return {*}
 */
const handleLayerEdit = (row: Layers.ResLayerListItem) => {
    layerEditModal.currentEditLayer.value = row
    layerEditModal.editState.value = true
}

onBeforeMount(() => {})
</script>

<style scoped lang="scss">
@import './index.scss';
</style>
<style lang="scss">
.overview-layer-operation-popover {
    width: 120px !important;
    min-width: 40px !important;
    ul {
        padding: 5px;
        margin: 0;
        list-style: none;
        li {
            display: flex;
            align-items: center;
            height: 24px;
            cursor: pointer;
            &:hover {
                color: rgb(7 155 253);
                background: #f2f3f5;
            }
            .operation-popover-title {
                margin-left: 4px;
            }
        }
    }
}
</style>
